package pl.edu.agh.gt.ga.greedy;

import java.util.Map;

import pl.edu.agh.gt.ga.Genotype;
import pl.edu.agh.gt.ga.MutationOperator;
import pl.edu.agh.gt.ga.Parameters;
import pl.edu.agh.gt.util.BetterRandom;

public class MutationImpl implements MutationOperator {
	
	@Override
	public Genotype mutate(Genotype genotype, Parameters params) {
		
		Map<String,Object> genes = genotype.getGenes();
		String [] names = new String [genes.size()]; 
		names = genes.keySet().toArray(names);
		
		int idx = BetterRandom.nextInt("mt", names.length);
		
		String name = names[idx];
		
		float biasFactor = BetterRandom.nextFloat("bf",0.5f,2.0f);
		
		Object oldVal = genotype.getGene(name);
		Object newVal = null;
		
		if( oldVal instanceof Float )
			newVal = new Float( (Float) oldVal * biasFactor);
		
		if( oldVal instanceof Integer )
			newVal = new Integer((int)(new Float((Integer)oldVal) * biasFactor));
		
		// repair new value if it is not acceptable
		newVal = Validator.validate(newVal, name);
		
		genotype.setGene(name, newVal);
			
		return genotype;
	}

}
